package com.alibaba.citrus.cr.mn.order.center.common.util;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Chen.mu
 * 2023/6/26
 **/
public class TrimUtils {

    public static void removeSpace(Object model) {
        Class<?> clazz = model.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {//向上循环 遍历父类
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field == null) {
                    continue;
                }
                field.setAccessible(true);
                try {
                    if (field.getGenericType().toString().equals("class java.lang.String")) {
                        Method getMethod = clazz.getMethod("get" + getMethodName(field.getName()));
                        String value = (String) getMethod.invoke(model);// 调用getter方法获取属性值
                        if (StringUtils.isNotEmpty(value)) {
                            value = value.trim();
                            field.setAccessible(true);
                            field.set(model, value);
                        }
                    }
                    if (List.class.isAssignableFrom(field.getType())) {
                        Type t = field.getGenericType();
                        if (t instanceof ParameterizedType) {
                            Object object = field.get(model);
                            if (ObjectUtil.isEmpty(object)) {
                                continue;
                            }
                            Class clazz1 = object.getClass();//获取到属性的值的Class对象
                            Method m = clazz1.getDeclaredMethod("size");
                            int size = (Integer) m.invoke(field.get(model));//调用list的size方法，得到list的长度
                            for (int i = 0; i < size; i++) {//遍历list，调用get方法，获取list中的对象实例
                                Method getM = clazz1.getDeclaredMethod("get", int.class);
                                if (!getM.isAccessible()) {
                                    getM.setAccessible(true);
                                }
                                removeSpace(getM.invoke(field.get(model), i));
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 返回首字母大写
     *
     * @param fildeName
     * @return
     * @throws Exception
     */
    private static String getMethodName(String fildeName) {
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }
}
